<?php
//Deal expires at 10 pm
include '../../../wp-blog-header.php';
require_once('rss_fetch.inc');

$url = $argv['2'];
//$url =  'http://www.feed43.com/'.$_GET['url'];
//$city = $_GET['city'];
$city = $argv['1'];

$brand_id = '730';
$rss = fetch_rss($url);
/*
echo "<pre>";
print_r($rss->items);
exit();
*/


if(!empty($rss->items) && is_array($rss->items))
{
  foreach($rss->items as $key=>$value)
  {
    $fetched_values = explode('~',$value['description']);
    $final_values = explode('$',$fetched_values['1']);
    
    /*
    echo '<pre>';
    print_r($final_values);
    echo '</pre>';
    exit();
    */
    
    $deal_link = ' http://affiliates.tyroodr.com/ez/cenxpksnl/';
    $name = $value['title'].' '.substr($final_values['1'],0,120);
    
    $columns_deal['name'] = pods_sanitize(ucwords(strtolower($name)));
    $columns_deal['camp_link'] = substr(sanitize_title($columns_deal['name']),0,128);
    
    $deal = new Pod('deal');
    $deal->page=1;
    $deal->search=false;
    $where = "t.camp_link = '".$columns_deal['camp_link']."' AND t.daily = 1";
    $deal->findRecords('id DESC', 1,$where);
    $dealsFound = $deal->getTotalRows();
    
    if($dealsFound == 0)
    {
      $city_pod = new Pod('city');
      $city_pod->page=1;
      $city_pod->search=false;
    	$city_pod->findRecords("name ASC",1,"t.name = '$city'");
    	while($city_pod->fetchRecord())
    	{
      	$city_id  = $city_pod->get_field('id');
    	}
      $columns_deal['city'] = $city_id;
      
      $shortened_url = make_bitly_url($deal_link);
      if(empty($shortened_url))
      {
        $shortened_url = make_goog_url($deal_link);
      }
      $columns_deal['extlink'] = $shortened_url;
      
      $columns_deal['camp_end'] = date('Y-m-d 22:00:00',strtotime('+1 day'));
      $columns_deal['camp_start'] = date('Y-m-d H:i:s');
      $columns_deal['brand'] = $brand_id;
      $columns_deal['daily'] = '1';
      $columns_deal['oriprice'] = $final_values['2'];
      $columns_deal['disprice'] = ($final_values['2'] - $final_values['4']);
    
      $columns_deal['disper'] = floor(((($columns_deal['oriprice'] - $columns_deal['disprice'])/$columns_deal['oriprice'])*100));
      
      $columns_deal['ext_image_url'] = $final_values['0'];
    
      $cat_id = check_daily_category($columns_deal['name']);
      if(!empty($cat_id))
      {
        $columns_deal['camp_cat'] = $cat_id;
      }
      
      $api = new PodAPI();
      $params = array('datatype' => 'deal', 'columns' => $columns_deal);
    
      /*
      echo '<pre>';
      print_r($params);
      echo '</pre>';
      */
      $api->save_pod_item($params);
    }
    
  }
}
?>
